﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualStudio.TeamFoundation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.VisualStudio.Shell;
using Microsoft.TeamFoundation.Framework.Client;
using System.Collections.ObjectModel;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.VisualStudio.TeamFoundation.WorkItemTracking;
using System.IO;

namespace VS2010.TFSHelperPackage
{
    public partial class CopyWorkItemAdvancedForm : Form
    {
        private IServiceProvider _serviceProvider;
        private IWorkItemTrackingDocument _currentDocument;
        private WorkItem _currentWorkItem;
        private WorkItem _newWorkItem;
        private WorkItemStore _workItemStore;

        public CopyWorkItemAdvancedForm(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            _serviceProvider = serviceProvider;
            LoadControls();
        }

        private void LoadControls()
        {
            this.cmbProjects.Items.Clear();
            this.cmbWorkItemTypes.Items.Clear();

            //Load source workitem 
            _currentDocument = WitDocumentHelper.GetCurrentWitDocument(_serviceProvider);
            string selectedItemId = string.Empty;
            if (_currentDocument is IResultsDocument)
            {
                int cnt = ((IResultsDocument)_currentDocument).SelectedItemIds.Length;
                if (cnt > 0)
                {
                    IResultsDocument resultDocument = (IResultsDocument)_currentDocument;                    
                    selectedItemId = resultDocument.SelectedItemIds[0].ToString();
                    //int[] itemIds = {resultDocument.SelectedItemIds[0]};
                    //_currentWorkItem = resultDocument.ResultListDataProvider.PageItems(itemIds)[0];
                    _currentWorkItem = resultDocument.ResultListDataProvider.GetItem(0);
                    //_currentWorkItem = resultDocument.ResultListDataProvider.GetItem(resultDocument.SelectedItemIds[0]);
                    //_currentWorkItem = resultDocument.WorkItems[0];
                }
            }
            else if (_currentDocument is IWorkItemDocument)
            {
               // To be completed
            }
            else if (_currentDocument is IQueryDocument)
            {
                // To be completed
            }
            else
            {
                // To be completed
            }

            this.Text = "Create Copy of Work Item with options ... [ " +  selectedItemId+"]";

            //Load dropdowns
            var dte = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            TeamFoundationServerExt ext = dte.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt") as TeamFoundationServerExt;
            TfsTeamProjectCollection teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(ext.ActiveProjectContext.DomainUri));

            // Refer to http://msdn.microsoft.com/en-us/library/bb286958.aspx for list of types available with GetService
            _workItemStore = teamProjectCollection.GetService<WorkItemStore>();

            if (_workItemStore != null)
            {
                if (_workItemStore.Projects.Count > 0)
                {
                    foreach (Project prj in _workItemStore.Projects)
                    {                        
                        this.cmbProjects.Items.Add(prj.Name);

                        if (this.cmbWorkItemTypes.Items.Count == 0)
                        {
                            foreach (WorkItemType wtype in prj.WorkItemTypes)
                            {
                                string wtypeName = wtype.Name;
                                if (!this.cmbWorkItemTypes.Items.Contains(wtypeName))
                                    this.cmbWorkItemTypes.Items.Add(wtypeName);
                            }
                        }

                    }
                }
            }


            this.cmbWorkItemTypes.SelectedIndex = this.cmbWorkItemTypes.Items.IndexOf(_currentWorkItem.Type.Name);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (_currentWorkItem != null)
            {
                CreateNewWorkItem();
                string message = string.Format("Copied Item Successfully !!! \r\n Source Item ID {0} has {1}  Attachments and {2} Links \r\n\r\n Target Item ID {3} has {4} Attachments and {5} Links", 
                    _currentWorkItem.Id,
                    _currentWorkItem.Attachments.Count,
                    _currentWorkItem.Links.Count,
                    _newWorkItem.Id,
                    _newWorkItem.Attachments.Count,
                    _newWorkItem.Links.Count);
                MessageBox.Show(message,this.Text,MessageBoxButtons.OK);
            }

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void CreateNewWorkItem()
        {

            Project targetProject = _workItemStore.Projects[this.cmbProjects.SelectedItem.ToString()];

            WorkItemType wit = targetProject.WorkItemTypes[this.cmbWorkItemTypes.SelectedItem.ToString()];

            _newWorkItem = _currentWorkItem.Copy(wit);
           
            RelatedLink source2Target = new RelatedLink(targetProject.Id);
            _newWorkItem.Links.Add(source2Target);

            System.Net.WebClient request = new System.Net.WebClient();
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            string tempPath = System.IO.Path.GetTempPath();
            if (_currentWorkItem.Attachments.Count > 0)
            {
                foreach (Attachment attach in _currentWorkItem.Attachments)
                {
                    string attachmentPath = Path.Combine(tempPath, attach.Name);
                    request.DownloadFile(attach.Uri, attachmentPath);
                    _newWorkItem.Attachments.Add(new Attachment(attachmentPath));
                    
                }
            }
            _newWorkItem.Save(SaveFlags.MergeLinks);
            //_newWorkItem.Save();

            #region comments
            //MessageBox.Show("Saved Successfully");

            // Create New WorkIten

            //WorkItemType wiType = proj.WorkItemTypes["Bug Fix"];

            //// Populate New WorkItem
            //WorkItem wi = new WorkItem(wiType);

            //wi.Fields["FCS.Common.ProductionSystem"].Value = getProductionSystem(wiIn.Fields["System.TeamProject"].Value.ToString());

            //wi.Fields["System.Title"].Value = wiIn.Fields["System.Title"].Value;

            //wi.Fields["System.Description"].Value = wiIn.Fields["System.Description"].Value;

            //wi.Fields["System.AssignedTo"].Value = wiIn.Fields["System.AssignedTo"].Value;

            //wi.Fields["FCS.Common.StatusCode"].Value = wiIn.Fields["FCS.Common.StatusCode"].Value;

            //wi.Fields["FCS.Common.Top10Priority"].Value = wiIn.Fields["FCS.Common.Top10Priority"].Value;

            //if (Convert.IsDBNull(wiIn.Fields["FCS.Common.DetectedDate"]))

            //{

            //wi.Fields["FCS.Common.DateRequested"].Value = wiIn.Fields["System.DateEntered"].Value;

            //}

            //else

            //{

            //wi.Fields["FCS.Common.DateRequested"].Value = wiIn.Fields["FCS.Common.DetectedDate"].Value;

            //}

            //wi.Fields["FCS.Common.ScheduledRelease"].Value = wiIn.Fields["FCS.Common.ScheduledRelease"].Value;

            //wi.Fields["FCS.Common.AssignedBA"].Value = wiIn.Fields["FCS.Common.AssignedBA"].Value;

            ////wi.Fields["FCS.Common.Owner1"].Value = wiIn.Fields["FCS.Common.Owner1"].Value;

            //wi.Fields["FCS.Common.BAHoursProjected"].Value = wiIn.Fields["FCS.Common.BAHoursProjected"].Value;

            //wi.Fields["FCS.Common.BAHoursActual"].Value = wiIn.Fields["FCS.Common.BAHoursActual"].Value;

            //wi.Fields["FCS.Common.DevHoursProjected"].Value = wiIn.Fields["FCS.Common.DevHoursProjected"].Value;

            //wi.Fields["FCS.Common.DevHoursActual"].Value = wiIn.Fields["FCS.Common.DevHoursActual"].Value;

            //wi.Fields["System.History"].Value = wiIn.Fields["System.History"].Value;

            ////wi.Fields["System.Attachments"].Value = wiIn.Fields["System.Attachments"].Value;

            //// Check for Attachments

            //if (wiIn.Attachments.Count > 0)

            //{

            //foreach (Attachment att in wiIn.Attachments)

            //{

            //wi.Attachments.Add(att);

            //}

            //}

            //// Check for Links

            //foreach (Link lnk in wiIn.Links)

            //{

            //wi.Links.Add(lnk);

            //}



            //// Check Validity

            //if (!FieldValidityCheck(wi))

            //{

            //Console.WriteLine("Validity Check Failed!");

            //}

            //else

            //{

            //// Save New WorkItem

            ////wi.Save();

            //}
            #endregion comments

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }
    }
}
